import React from 'react';
import { connect } from 'react-redux';
import { bindActionCreators } from 'redux';
import consts from '../../../utils/consts';
import editorTypes from '../../../consts/editorTypes';
import Paging from './Paging';
import PreviewDialog from '../../dialog/PreviewDialog';
import dialogAction from '../../../actions/Editor/dialog';
import editorAction from '../../../actions/Editor/editor';

class EditorTypeChecker extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            editorType: editorTypes.UNCHECKED,
            templateId: '',
            pageIndex: 1,
            pageSize: 8,
        };
    }
    componentDidMount() {
        this.bindEvent();
    }

    bindEvent() {
        $(this.refs.templates).delegate('ul > li', 'mouseenter', function () {
            let me = $(this),
                div = me.find('.template-item-pre');
            div.stop().animate({
                bottom: 35,
            });
        }).delegate('ul > li', 'mouseleave', function () {
            let me = $(this),
                div = me.find('.template-item-pre'),
                h = div.height();
            div.stop().animate({
                bottom: `-${2 * h}px`,
            });
        });
    }
    handleOnCreateEditor() {
        const { saveEditorType } = this.props;
        saveEditorType(editorTypes.EDITOR);
    }
    handleOnCheckEditor() {
        this.setState({
            editorType: 'editor',
        });
    }
    handleOnCheckTemplate() {
        this.setState({
            editorType: 'template',
            pageIndex: 1,
        });
    }
    handleOnSelectTemplate(e) {
        const className = 'template-item-main';
        let element = $(e.target || e.srcElement);
        element = element.hasClass(className) ? element : element.parents(`.${className}`);
        const id = element.attr('data-id');

        this.setState({
            templateId: id,
        });
    }
    handleOnPreviewData(e) {
        const className = 'template-item-main';
        let element = $(e.target || e.srcElement);
        element = element.hasClass(className) ? element : element.parents(`.${className}`);
        const id = element.attr('data-id');
        const data = this.getSpecifyTemplateById(id);

        const { openDialog, closeDialog } = this.props;
        openDialog('public/preview', PreviewDialog, data, {
            closeDialog,
        });

        return false;
    }
    handleOnCreateTemplate() {
        const { saveEditorType, createTemplate } = this.props;
        const { templateId } = this.state;

        saveEditorType(editorTypes.TEMPLATE);
        const template = this.getSpecifyTemplateById(templateId);
        const resourcePictureId = template.picture.resource_picture_id;
        createTemplate(resourcePictureId);
    }
    getSpecifyTemplateById(id) {
        const templates = this.props.templates;
        const result = templates.filter((template) => {
            return template.resource_id == id;
        });
        return result.length ? result[0] : null;
    }
    setPageSize(pageIndex) {
        this.setState({
            pageIndex,
        });
    }
    render() {
        const { templates, dialog, closeDialog } = this.props;
        const { pageIndex, pageSize, templateId, editorType } = this.state;
        const curTemplates = templates.slice((pageIndex - 1) * pageSize, pageIndex * pageSize);

        return (
          <div className={`editor-checker ${this.props.editorType === editorTypes.UNCHECKED ? '' : 'hide'}`}>
            <div className="region">
              <div className="tip">{$._('Choose editor type and can not switch')}</div>
              <div className="modal-region">
                <div onClick={e => this.handleOnCheckEditor(e)} className={`modal-item ${editorType === 'editor' ? 'active' : ''}`}>
                  <div className="button-item">
                    <div className="top">
                      <div className="icon">
                        <img src={`${window.is.CONST.root_path}/image/icon/icon_editor_ar.svg`} />
                      </div>
                      <div className="name">
                        {$._('Editor AR')}
                      </div>
                    </div>
                    <div className="bottom">
                      <ul>
                        <li>{$._('Suitable for advanced content editing')}</li>
                        <li>{$._('Completely customized content design')}</li>
                      </ul>
                    </div>
                  </div>
                </div>
                <div className={`modal-item ${editorType === 'template' ? 'active' : ''}`} onClick={e => this.handleOnCheckTemplate(e)}>
                  <div className="button-item">
                    <div className="top">
                      <div className="icon">
                        <img src={`${window.is.CONST.root_path}/image/icon/icon_template_ar.svg`} />
                      </div>
                      <div className="name">
                        {$._('template AR')}
                      </div>
                    </div>
                    <div className="bottom">
                      <ul>
                        <li>{$._('No threshold for a fool Style Editor')}</li>
                      </ul>
                    </div>
                  </div>
                </div>
              </div>
            </div>
            <div className="editorChecker" style={{ display: (editorType === 'editor' ? 'block' : 'none') }}>
              <div>
                <button onClick={e => this.handleOnCreateEditor(e)} className="button">
                  <span className="button-item"><span className="text-grad">{$._('Create AR')}</span></span>
                </button>
              </div>
              <div className="editor-checker-tip">{$._('you will not be able to switch')}</div>
            </div>
            <div className="list" style={{ display: (editorType === 'template' ? 'block' : 'none') }}>
              <div className="header">
                <span className="title">{$._('AR template')}</span>
                <button onClick={e => this.handleOnCreateTemplate(e)} disabled={templateId === ''} className={`button ${templateId == '' ? 'disabled' : ''}`}>
                  <span className="button-item"><span className="text-grad">{$._('Create AR')}</span></span>
                </button>
              </div>
              <div ref="templates" className="content">
                <ul>
                  {
                    curTemplates.map((template) => {
                        return (
                          <li className={`template-item ${templateId === template.resource_id ? 'selected' : ''}`} key={template.resource_id} >
                            <div className="template-item-main" onClick={e => this.handleOnSelectTemplate(e)} data-id={template.resource_id}>
                              <img src={template.picture.thumbnail_media_src} />
                              <div className="template-item-pre" onClick={e => this.handleOnPreviewData(e)}>{$._('Preview')}</div>
                              <div className="template-item-title">{template.resource_tag_title}</div>
                            </div>
                          </li>
                        );
                    })
                  }
                </ul>
              </div>
              <Paging total={templates.length} pageSize={pageSize} onPageSizeChange={index => this.setPageSize(index)} />;
            </div>
            <div className="dialog-cover" style={{ display: dialog.type === 'public/preview' ? 'block' : 'none' }} onClick={closeDialog} />
          </div>
        );
    }
}

const mapStateToProps = ({ templates, editor, dialog }) => {
    return {
        templates,
        editorType: editor.editorType,
        dialog,
    };
};

const mapDispatchToProps = (dispatch) => {
    return bindActionCreators({ ...dialogAction, ...editorAction }, dispatch);
};

export default connect(mapStateToProps, mapDispatchToProps)(EditorTypeChecker);
